using Microsoft.EntityFrameworkCore;
using MediPlatform.Infeartructure;
using MediPlatform.Read.Api.Models;
using MediPlatform.Domain.Order;

namespace MediPlatform.Read.Api.Services
{
    public class RegistrationOrderService
    {
        private readonly MyDbContext _context;
        private readonly ILogger<RegistrationOrderService> _logger;

        public RegistrationOrderService(MyDbContext context, ILogger<RegistrationOrderService> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 获取挂号订单分页列表
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <returns>分页结果</returns>
        public async Task<RegistrationOrderPagedResponse> GetPagedListAsync(RegistrationOrderQueryRequest request)
        {
            try
            {
                _logger.LogInformation("开始查询挂号订单分页列表，页码：{PageIndex}，页大小：{PageSize}", request.PageIndex, request.PageSize);

                var query = _context.RegistrationOrder
                    .Include(ro => ro.User)
                    .AsQueryable();

                // 根据订单号或用户名筛选
                if (!string.IsNullOrWhiteSpace(request.OrderNoOrUsername))
                {
                    query = query.Where(ro => 
                        (ro.OrderNo != null && ro.OrderNo.Contains(request.OrderNoOrUsername)) ||
                        (ro.User != null && ro.User.Username != null && ro.User.Username.Contains(request.OrderNoOrUsername))
                    );
                }

                // 根据时间范围筛选
                if (request.StartTime.HasValue)
                {
                    query = query.Where(ro => ro.CreatedAt >= request.StartTime.Value);
                }

                if (request.EndTime.HasValue)
                {
                    var endTime = request.EndTime.Value.AddDays(1).AddSeconds(-1);
                    query = query.Where(ro => ro.CreatedAt <= endTime);
                }

                // 根据状态筛选
                if (request.Status.HasValue)
                {
                    query = query.Where(ro => ro.Status == request.Status.Value);
                }

                var totalCount = await query.CountAsync();

                var items = await query
                    .OrderByDescending(ro => ro.CreatedAt)
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .Select(ro => new RegistrationOrderListItem
                    {
                        Id = ro.Id,
                        OrderNo = ro.OrderNo,
                        CreatedAt = ro.CreatedAt,
                        Username = ro.User != null ? ro.User.Username : null,
                        DoctorName = GetDoctorName(ro.DoctorId),
                        DepartmentName = GetDepartmentName(ro.DepartmentId),
                        Fee = ro.Fee,
                        Status = ro.Status,
                        StatusText = GetStatusText(ro.Status)
                    })
                    .ToListAsync();

                var result = new RegistrationOrderPagedResponse
                {
                    Items = items,
                    TotalCount = totalCount,
                    TotalPages = (int)Math.Ceiling((double)totalCount / request.PageSize),
                    CurrentPage = request.PageIndex,
                    PageSize = request.PageSize
                };

                _logger.LogInformation("挂号订单分页查询完成，总记录数：{TotalCount}，总页数：{TotalPages}", totalCount, result.TotalPages);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询挂号订单分页列表失败");
                throw;
            }
        }

        /// <summary>
        /// 获取挂号订单详情
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>订单详情</returns>
        public async Task<RegistrationOrderDetailResponse?> GetDetailAsync(long id)
        {
            try
            {
                _logger.LogInformation("开始查询挂号订单详情，订单ID：{OrderId}", id);

                var order = await _context.RegistrationOrder
                    .Include(ro => ro.User)
                    .FirstOrDefaultAsync(ro => ro.Id == id);

                if (order == null)
                {
                    _logger.LogWarning("挂号订单不存在，订单ID：{OrderId}", id);
                    return null;
                }

                var result = new RegistrationOrderDetailResponse
                {
                    Success = true,
                    OrderInfo = new RegistrationOrderInfo
                    {
                        Id = order.Id,
                        OrderNo = order.OrderNo,
                        UserId = order.UserId,
                        Username = order.User?.Username,
                        UserPhone = order.User?.PhoneNumber,
                        HospitalId = order.HospitalId,
                        HospitalName = GetHospitalName(order.HospitalId),
                        DepartmentId = order.DepartmentId,
                        DepartmentName = GetDepartmentName(order.DepartmentId),
                        DoctorId = order.DoctorId,
                        DoctorName = GetDoctorName(order.DoctorId),
                        ScheduleTime = order.ScheduleTime,
                        Status = order.Status,
                        StatusText = GetStatusText(order.Status),
                        Fee = order.Fee,
                        DiscountAmount = order.DiscountAmount,
                        ActualPayment = order.ActualPayment,
                        PaymentMethod = order.PaymentMethod,
                        PaymentTime = order.PaymentTime,
                        RefundAmount = order.RefundAmount,
                        RefundTime = order.RefundTime,
                        CancelReason = order.CancelReason,
                        ExtraInfo = order.ExtraInfo,
                        CreatedAt = order.CreatedAt,
                        UpdatedAt = order.UpdatedAt
                    }
                };

                _logger.LogInformation("挂号订单详情查询完成，订单ID：{OrderId}", id);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询挂号订单详情失败，订单ID：{OrderId}", id);
                throw;
            }
        }

        /// <summary>
        /// 获取挂号订单统计数据
        /// </summary>
        /// <returns>统计数据</returns>
        public async Task<RegistrationOrderStatisticsResponse> GetStatisticsAsync()
        {
            try
            {
                _logger.LogInformation("开始查询挂号订单统计数据");

                var totalCount = await _context.RegistrationOrder.CountAsync();
                var pendingPaymentCount = await _context.RegistrationOrder.CountAsync(ro => ro.Status == 0);
                var completedCount = await _context.RegistrationOrder.CountAsync(ro => ro.Status == 1);
                var cancelledCount = await _context.RegistrationOrder.CountAsync(ro => ro.Status == 2);
                var refundedCount = await _context.RegistrationOrder.CountAsync(ro => ro.Status == 3 || ro.Status == 4);

                var result = new RegistrationOrderStatisticsResponse
                {
                    TotalCount = totalCount,
                    PendingPaymentCount = pendingPaymentCount,
                    CompletedCount = completedCount,
                    CancelledCount = cancelledCount,
                    RefundedCount = refundedCount
                };

                _logger.LogInformation("挂号订单统计数据查询完成，总订单数：{TotalCount}", totalCount);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询挂号订单统计数据失败");
                throw;
            }
        }

        /// <summary>
        /// 获取状态文本
        /// </summary>
        /// <param name="status">状态值</param>
        /// <returns>状态文本</returns>
        private static string GetStatusText(int? status)
        {
            return status switch
            {
                0 => "待支付",
                1 => "已完成",
                2 => "已取消",
                3 => "已退款",
                4 => "已退款", // 兼容状态4
                _ => "未知状态"
            };
        }

        /// <summary>
        /// 获取医生姓名
        /// </summary>
        /// <param name="doctorId">医生ID</param>
        /// <returns>医生姓名</returns>
        private static string GetDoctorName(long? doctorId)
        {
            // 这里应该从数据库查询医生信息，暂时返回模拟数据
            if (!doctorId.HasValue)
                return "普通号";

            return doctorId switch
            {
                1 => "张三",
                2 => "李四",
                3 => "王五",
                _ => $"医生{doctorId}"
            };
        }

        /// <summary>
        /// 获取科室名称
        /// </summary>
        /// <param name="departmentId">科室ID</param>
        /// <returns>科室名称</returns>
        private static string GetDepartmentName(long? departmentId)
        {
            // 这里应该从数据库查询科室信息，暂时返回模拟数据
            if (!departmentId.HasValue)
                return "未知科室";

            return departmentId switch
            {
                1 => "内科",
                2 => "外科",
                3 => "儿科",
                4 => "妇产科",
                5 => "骨科",
                _ => $"科室{departmentId}"
            };
        }

        /// <summary>
        /// 获取医院名称
        /// </summary>
        /// <param name="hospitalId">医院ID</param>
        /// <returns>医院名称</returns>
        private static string GetHospitalName(long? hospitalId)
        {
            // 这里应该从数据库查询医院信息，暂时返回模拟数据
            if (!hospitalId.HasValue)
                return "未知医院";

            return hospitalId switch
            {
                1 => "第一人民医院",
                2 => "第二人民医院",
                3 => "中医院",
                _ => $"医院{hospitalId}"
            };
        }
    }
} 